<?php

namespace app\api\controller\v1;

use addons\litestore\model\Litestoregoodsspec;
use addons\litestore\model\Litestoreorder;
use addons\litestore\model\Wxlitestoregoods;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestorenews;
use app\admin\model\Pingoods;
use app\admin\model\Pinjoin;
use app\admin\model\Pinprofit;
use app\admin\model\Pinuser;
use app\admin\model\unilive\Room;
use app\admin\model\Useraddress;
use app\admin\model\Userrelation;
use app\admin\model\Userweixin;
use app\api\service\LepayService;
use app\api\service\Orderservice;
use app\common\controller\Api;

/**
 * 拼团接口
 */
class Pin extends Api
{
    protected $noNeedLogin = ['callback', 'doPin','pinUserList'];
    protected $noNeedRight = ['*'];

    public function index()
    {

        $page = $this->request->param('page');
        $pinGoodsModel = new Pingoods();
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $list = $pinGoodsModel->with(['good'])->
        limit($offset, $limit)
            ->select();

        foreach ($list as $key => $val) {

            $good = $val['good'];
            $images = explode(",", $good['images']);
            $good['image'] = cdnurl($images[0], true);
            $list[$key]['good'] = $good;
        }
        $this->success('', $list);
    }


    public function detail()
    {
        $goods_id = $this->request->param('goods_id');
        $pinid = $this->request->param('pinid');

        $pingoodsModel = new Pingoods();
        $pin = $pingoodsModel->where('id', $pinid)->find();
        if (!$pin) {
            $this->error('很抱歉，拼团已下线');
        }

        error_log("==detail==1=" . json_encode($goods_id));

        // 商品详情
        $detail = Wxlitestoregoods::detail($goods_id);
        error_log("==detail===" . json_encode($detail));
        $imgs = [];
        foreach (explode(",", $detail['images']) as $index => $item) {
            $imgs[] = cdnurl($item, true);
        }
        $detail['imgs_url'] = $imgs;

        if (!$detail || $detail['goods_status'] !== '10') {
            $this->error('很抱歉，商品信息不存在或已下架');
        }
        // 规格信息
        $specData = $detail['spec_type'] === '20' ? $detail->getManySpec($detail['spec_rel'], $detail['spec']) : null;

        // 这里对规格的img格式化
        if ($specData != null) {
            foreach ($specData['spec_list'] as $index => $item) {
                $specData['spec_list'][$index]["form"]['imgshow'] = $specData['spec_list'][$index]["form"]['spec_image'] === '' ? null : cdnurl($specData['spec_list'][$index]["form"]['spec_image'], true);
            }
        }
        $detail['content'] = preg_replace(
            array(
                '/(<img [^<>]*?)width=.+?[\'|\"]/',
                '/(<img.*?)((height)=[\'"]+[0-9|%]+[\'"]+)/',
                '/(<img.*?)((style)=[\'"]+(.*?)+[\'"]+)/',
            ), array('$1 width="90%" ', '$1', '$1'), $detail['content']);

        $images = explode(",", $detail['images']);
        foreach ($images as $k => $v) {
            $images[$k] = cdnurl($v, true);
        }
        $detail['images'] = $images;
        $this->success('', [
            'detail' => $detail,
            'specData' => $specData,
            'pin' => $pin
        ]);
    }

    public function buyNow_pay()
    {

        $user = $this->auth->getUser();
        $goods_id = $this->request->param('goods_id');
        $goods_num = $this->request->param('goods_num');
        $goods_sku_id = $this->request->param('goods_sku_id');
        $seller_id = $this->request->param('uid');
        $pinid = $this->request->param('pinid');
        if(!$seller_id){
            $seller_id = $user['ref_uid'];
        }
        $pinModel = new Pingoods();
        $pin = $pinModel->where('id', $pinid)->find();


        $litestoregoodsspec = new Litestoregoodsspec();
        $goods = $litestoregoodsspec->where('goods_id', $goods_id)->where('goods_spec_id', $goods_sku_id)->find();

        $userAddressModel = new Useraddress();
        $address = $userAddressModel->where('uid', $user['id'])->find();
        if (!$address) {
            $this->error('请添加收货地址');
        }
        $userWxModel = new Userweixin();
        $wx = $userWxModel->where('uid', $user['id'])->find();

        $goodModel = new Litestoregoods();
        $good = $goodModel->where('goods_id', $goods_id)->find();


        $orderNo = getOrderSn();
        $data = array();
        $data['desc'] = $good['goods_name'];
        $data['openid'] = $wx['openid'];

        $data['orderNo'] = $orderNo;
        $data['num'] = $goods_num;
        $data['amount'] = $goods_num * $pin['pprice'] * 100;

        $ratio = 100;

        $group_id = $user['group_id'];
        $data['pay_price'] = $goods_num * $pin['pprice'] * 100;
        $data['callback_url'] = 'https://' . $_SERVER['HTTP_HOST'] . "/api/v1/pin/callback";

        $payService = new LepayService("3910718329", "");
        $ret = $payService->pay2($data);

        error_log("====ret===" . json_encode($ret));
        if ($ret['resp_code'] == 0) {

            $data['goods'] = $goods;
            $data['address'] = $address;
            $data['seller_id'] = $seller_id;
            $data['ratio'] = $ratio;
            $data['pinid'] = $pinid;

            $liteorder = new \app\admin\model\litestore\Litestoreorder();
            $id = $liteorder->addPinOrder($user['id'], $data);
            if ($id) {
                $info = array();
                $info['orderNo'] = $orderNo;
                $info['payInfo'] = json_decode($ret['jspay_info'], true);
                $this->success('下单成功', $info);
            } else {
                $this->error("下单失败，请联系客服");
            }

        } else {
            $this->error("下单失败，请联系客服");
        }

    }

    public function callback()
    {

        $param = file_get_contents("php://input");
        error_log("======agent pay=====callback=================" . $param);

        $jsonxml = json_encode(simplexml_load_string($param, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);
//        error_log("========1====" . json_encode($result));
        $orderNo = $result['third_order_id'];
        $status = $result['status'];


        if ($status == 2) {
            $literOrder = new \app\admin\model\litestore\Litestoreorder();
            $order = $literOrder->where('order_no', $orderNo)->find();
            $literOrder->where('order_no', $orderNo)->update(['order_status' => 'payed',
                'pay_time' => time(), 'transaction_id' => $result['out_transaction_id']]);
            $pinUser = new Pinuser();
            $pinUser->insert(['uid' => $order['user_id'], 'pinid' => $order['pinid'], 'createtime' => time(), 'orderid' => $order['id']]);
        }
        echo "000000";
    }


    /**
     * 用户拼团列表
     */
    public function pinList()
    {

        $user = $this->auth->getUser();

        $liteorderModel = new \app\admin\model\litestore\Litestoreorder();
        $where = array();
        $where['pinid'] = ['<>', -1];
        $where['order_status'] = ['<>', 'paying'];
        $where['user_id'] = $user['id'];

        $list = $liteorderModel->with(['goods'])
            ->where($where)
            ->order(['createtime' => 'desc'])->limit(50)
            ->select();
        foreach ($list as $key => $val) {
            $images = explode(",", $val['goods'][0]['images']);
            foreach ($images as $k => $v) {
                $images[$k] = cdnurl($v, true);
            }
            $list[$key]['goods_name'] = $val['goods'][0]['goods_name'];
            $list[$key]['image'] = $images[0];
        }
        $this->success('', $list);
    }

    /**
     * 拼团中心
     */
    public function pinCenter()
    {
        $user = $this->auth->getUser();
        $data = array();


        $profitModel = new Pinprofit();
        $amount = $profitModel->where('uid', $user['id'])->sum('amount');

        $pinUserModel = new Pinuser();
        $pinUser = $pinUserModel->where('uid', $user['id'])->find();
        $data['total'] = $pinUser['join'];
        $data['profit'] = sprintf("%.2f",$amount);
        $this->success('', $data);
    }

    /**
     * 拼团收益
     */
    public function profitList()
    {
        $user = $this->auth->getUser();

        $page = $this->request->param('page');
        $pinProfitModel = new Pinprofit();
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = array();
        $where['uid'] = $user['id'];
        $list = $pinProfitModel->with(['goods'])
            ->where($where)
            ->limit($offset, $limit)
            ->order('createtime', 'desc')
            ->select();
        foreach ($list as $key => $val) {

            $list[$key]['goods_name'] = $val['goods'][0]['goods_name'];
            $list[$key]['createtime'] = date('Y-m-d h:i:s', $val['createtime']);
        }
        $this->success('', $list);

    }


    //拼团计算
    public function doPin()
    {



        error_log("========doPin========".date('Y-m-d h:i:s',time()));
        $litestoreOrderModel = new Litestoreorder();
        $pinModel = new \app\admin\model\Pin();
        $pin = $pinModel->order('createtime', 'desc')->find();
//        $startToday = strtotime(date("Y-m-d") . " 09:00:00");
//        $endToday = strtotime(date("Y-m-d") . " 10:00:00");

        $startToday2 = strtotime(date("Y-m-d") . " 15:00:00");
        $endToday2 = strtotime(date("Y-m-d") . " 16:00:00");

        $pinProfitModel = new Pinprofit();
        $time = time();
        if (($time >= $startToday2 && $time <= $endToday2)) {


            $pinUserModel = new Pinuser();
            $total = $pinUserModel->where('status', '<>', 'win')->count('id');

            $offset = 20;
            $page = ceil($total/$offset);

            error_log("===page====".$page);

            $list = array();
            for ($i = 1;$i<=$page;$i++){
                $pinUserList = $pinUserModel->where('status', '<>', 'win')->order('createtime', 'asc')->limit(($i-1)*$offset, $offset)->select();
                $list[] = $pinUserList;

            }

            foreach ($list as $key=>$val){
                $pinUserList = $val;
                $win = "";
                for ($i = 0;$i<5;$i++){
                    $key = rand(0, count($pinUserList)-1);
                    $obj = $pinUserList[$key];
                    $p = $pinUserModel->where('uid',$obj['uid'])->where('status','win')->find();
                    if($p){
                        continue;
                    }else{
                        $win = $obj;
                        break;
                    }
                }
                if(!$win){
                    $key = rand(0, count($pinUserList)-1);
                    $win = $pinUserList[$key];
                }

                $pinData = array();
                $pinData['createtime'] = $time;
                $pinData['join_num'] = count($pinUserList);
                $id = $pinModel->insertGetId($pinData);

                $pinJoinModel = new Pinjoin();
                $userRelation = new Userrelation();
                foreach ($pinUserList as $key=>$val){

                    $status = 'unwin';
                    if($val['id'] == $win['id']){
                        $status = 'win';
                        $litestoreOrderModel->where('id',$val['orderid'])->update(['pinstatus'=>'win','pinid'=>$id]);
                        $pinUserModel->where('id',$val['id'])->update(['updatetime'=>$time,'status'=>'win','join'=>($val['join']+1)]);
                    }else{
                        $litestoreOrderModel->where('id',$val['orderid'])->update(['pinid'=>$id]);
                        $pinUserModel->where('id',$val['id'])->update(['updatetime'=>$time,'status'=>'unwin','join'=>($val['join']+1)]);
                    }

                    $pinJoinModel->insert(['uid'=>$val['uid'],'createtime'=>$time,'status'=>$status,'pid'=>$id]);
                    if($status == 'unwin'){
                        $pinProfitModel->insert(['uid'=>$val['uid'],'orderid'=>$val['orderid'],'pinid'=>$id,'createtime'=>$time,'amount'=>1,'type'=>'self']);
                        $uid = $val['uid'];
                        $userRel = $userRelation->where('uid',$uid)->find();
                        $relArray = explode(",", $userRel['relation']);
                        if (count($relArray) >= 2) {
                            $ref_uid = $relArray[0];//直推
                            $two_ref_uid = $relArray[1];//间推
                            $pinProfitModel->insert(['uid'=>$two_ref_uid,'orderid'=>$val['orderid'],'pinid'=>$id,'createtime'=>$time,'amount'=>0.1,'type'=>'two']);
                        }else{
                            $ref_uid = $relArray[0];//直推
                        }
                        $pinProfitModel->insert(['uid'=>$ref_uid,'orderid'=>$val['orderid'],'pinid'=>$id,'createtime'=>$time,'amount'=>0.2,'type'=>'one']);
                    }
                }
            }

            echo "完成";

        }

    }

    public function pinUserList(){

       $id =  $this->request->param('id');

       $pinJoinModel = new Pinjoin();
       $list = $pinJoinModel->with(['user'])->where('pid',$id)->select();

       $array = array();
       foreach ($list as $key=>$val){
           $obj = array();
           $obj['name'] = $val['user']['username'];
           $obj['status'] = $val['status'];

           $array[] = $obj;

       }
       $this->success('',$array);
    }



}
